<template>
  <div>
    <el-form class="query-form" @submit.native.prevent :inline="true">
      <el-form-item>
        <el-input
          v-model="params.goods_name"
          :clearable="true"
          placeholder="主体名称查询"
          @change="getData"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="getData()">查询</el-button>
      </el-form-item>

      <el-form-item class="float-right">
        <el-button type="primary" icon="el-icon-plus" @click="handleEdit()">新增</el-button>

        <el-button
          type="primary"
          icon="el-icon-download"
          :loading="exportLoading"
          @click="handleExportAsync()"
        >
          {{ downloadText }}
        </el-button>

        <el-button type="primary" icon="el-icon-download" @click="handleExportSync()">
          导出(后端、同步)
        </el-button>

        <el-button type="primary" icon="el-icon-download" @click="handleExportJson()">
          导出(前端、JSON)
        </el-button>
      </el-form-item>
    </el-form>

    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData"></c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import { excelJsonExport, downloadByLink } from '@vimi/utils-tool'
import { queryUrl } from '@vimi/utils-api'

export default {
  components: {},
  props: {},
  data() {
    return {
      tableName: 'customer_related',
      tableId: '',
      params: {
        index: 1,
        size: 15,
      },
      loading: false,
      exportLoading: false,
      exportPercent: 0,

      // 表格
      tableData: [],
      tableCount: 0,
      tableColumns: [
        { attrs: { label: '所属地区', prop: 'address' } },
        {
          attrs: { label: '主体名称', prop: 'customer_name' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '营业执照号', prop: 'register_no' } },
        { attrs: { label: '经营者姓名', prop: 'contact_person' } },
        { attrs: { label: '身份证号码', prop: 'lender_idcard' } },
        { attrs: { label: '联系电话', prop: 'mobile_no' } },
        { attrs: { label: '创建用户', prop: 'submit_person_name' } },
        { attrs: { label: '创建时间', prop: 'create_time' } },
        {
          attrs: { label: '操作', align: 'center', minWidth: '120px' },
          operations: [
            { content: '修改', icon: 'fa fa-edit', event: this.handleEdit },
            { content: '归集', icon: 'fa fa-hourglass-2', event: this.handleFile },
            { content: '查看', icon: 'fa fa-search', event: this.handleView },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger py-0 px-2' },
              event: this.handleDelete,
            },
          ],
        },
      ],
    }
  },
  computed: {
    downloadText() {
      return this.exportLoading ? `${this.exportPercent}%` : '导出(后端、异步)'
    },
  },
  watch: {},
  created() {
    this.getData()
  },
  mounted() {},
  methods: {
    async getData() {
      this.loading = true
      let [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, this.params, { create_time: 'desc' })
      )
      this.loading = false
      this.tableData = (res && res.data && res.data.data) || []
      this.tableCount = res && res.data && res.data.totalCount
    },
    handleEdit() {},
    handleDelete() {},
    handleFile() {},
    handleView() {},

    /**
     * 导出方法1：
     * 1、同步（无法监听api错误和下载进度）
     * 2、打开excel不会出现受保护的视图
     */
    handleExportSync() {
      const params = {
        service: this.$serviceName,
        table: this.tableName,
        params: this.params,
        filename: '经营主体信息.xlsx',
        accept: 'application/octet-stream',
      }

      // 需要 import { downloadByLink } from '@/common/plugins/tools/export'
      downloadByLink({
        url: queryUrl(params),
        filename: '经营主体信息.xlsx',
      })
    },

    /**
     * 导出方法2：
     * 1、异步
     * 2、可以监听api错误和下载进度
     * 3、打开excel会出现受保护的视图(因为是来自 internet 的文件，可以excel设置中取消)
     */
    async handleExportAsync() {
      this.exportLoading = true
      this.exportPercent = 0

      const params = {
        service: this.$serviceName,
        table: this.tableName,
        params: this.params,
        filename: '经营主体信息.xlsx',
      }

      // 监听下载进度
      params.onDownloadProgress = progressEvent => {
        const loaded = progressEvent.loaded
        const response = progressEvent.target.response || {}
        const total = response.size || 0
        this.exportPercent = total > 0 ? (loaded / total) * 100 : 0
      }

      // 使用$api.downloadData下载
      await this.$utils.promise(this.$api.exportData(params))

      this.exportPercent = 0
      this.exportLoading = false
    },

    /**
     * 导出方法3：
     * 1、同步，导出不需要调用API
     * 2、只能导出 json 数据类型的文件（通过API请求后的数据）
     * 3、除非已经全部获取了所有数据，否则无法导出所有数据
     * 4、可自定义导出内容，包括表头、列宽、合并单元格、字体样式(TODO)等
     *
     * 需要导入file-save和xlsx包，会大大增加打包体积（+900kb）
     * 已改用cdn方式
     */
    handleExportJson() {
      const exportTable = this.tableColumns.filter(item => !item.operations)
      // 添加自定义表头
      const header = {}
      const columns = exportTable.map(item => {
        const key = (item.attrs && item.attrs.prop) || 'key'
        header[key] = (item.attrs && item.attrs.label) || ''
        return key
      })

      // 需要 import { excelJsonExport } from '@/common/plugins/tools/export'
      excelJsonExport({
        columns,
        data: [header, ...this.tableData],
        filename: '经营主体信息', // 不要传文件类型
        merges: ['A2:B3'], // 可以合并单元格
        // bookType: 'xlsx',
        // autoWidth: true
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
